package com.ybkj.daijia.server;

import com.ybkj.daijia.InfoFeeType;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.server.mapper.OrderMapper;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class InstantiationTracingBeanPostProcessor implements
    ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    public static void main(String[] args) {

    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            try {
                check();
                checkWxSetting();
            } catch (Exception e) {
                e.printStackTrace();
            }


        } else {
            ++ThreadControl.setupTime;
            if (ThreadControl.setupTime == 1) {

                if (ThreadControl.SysAutoRunning) {
                    Setting setting = settingUtils.get();
                    List<Order> newOrders = orderMapper
                        .selectByCompanyWithStatus(null, Order.ORDER_STATUS_NEW, null);
                    if (!CollectionUtils.isEmpty(newOrders)) {
                        for (Order order : newOrders) {

                            Timer timer = new Timer();
                            OrderTimerTask orderTimerTask = new OrderTimerTask(
                                setting.getAutoPaidanKm1(), setting.getAutoPaidanTime1(),
                                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                                setting.getAutoPaidanKm3(), setting.getAutoPaidanTime3(),
                                applicationEventMulticaster,
                                order.getId(), order.getClientLatitude(),
                                order.getClientLongitude(), 1
                            );
                            timer.schedule(orderTimerTask, setting.getAutoPaidanTime1() * 1000);
                            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);

                        }
                    }
                }

            }
        }

    }

    public void check() throws Exception {
        Setting defaultSetting = getDefaultSetting();
        Map<String, Field> fieldMap = new HashMap<>();
        Class clz = Setting.class;
        Resource resource = new ClassPathResource("setting.xml");
        SAXReader reader = new SAXReader();
        Resource resourceWx = new ClassPathResource("wxsetting.xml");
        SAXReader readerWx = new SAXReader();
        Document doc = reader.read(resource.getInputStream());
        Element root = doc.getRootElement();

        for (Field field : clz.getDeclaredFields()) {
            String name = field.getName();
            fieldMap.put(name, field);
        }

        @SuppressWarnings("unchecked")
        Iterator<Element> iter = root.elementIterator();
        Map<String, Object> xmlMap = new HashMap<>();
        Map<String, Element> nodeMap = new HashMap<>();
        while (iter.hasNext()) {
            Element element = iter.next();
            Iterator<Element> it = element.elementIterator();
            String name = element.getName();
            Object value = null;
            if (it.hasNext()) {
                Map<String, Object> valueMap = new HashMap<>();
                while (it.hasNext()) {
                    Element tempElement = it.next();
                    valueMap.put(tempElement.getName(), tempElement.getTextTrim());
                    xmlMap.put(tempElement.getName(), tempElement.getTextTrim());
                    value = valueMap;
                    nodeMap.put(name, tempElement);
                }
            } else {
                value = element.getTextTrim();
            }

            xmlMap.put(name, value);
        }
        for (String fielKey : fieldMap.keySet()) {
            Object value = xmlMap.get(fielKey);
            if (value == null) {
                Element element = root.addElement(fielKey);
                Field field = fieldMap.get(fielKey);
                field.setAccessible(true);
                Object v = field.get(defaultSetting);
                if (v == null) {
                    element.setText("");
                } else {
                    element.setText(String.valueOf(v));
                }
                //可以在这里手动赋值
            }
        }
        OutputFormat of = OutputFormat.createPrettyPrint();
        of.setEncoding("UTF-8");
        of.setIndent(true);
        of.setIndent("\t");
        of.setNewlines(true);
        XMLWriter writer = new XMLWriter(new FileOutputStream(
            resource.getFile()), of);
        writer.write(doc);
        writer.flush();
        writer.close();
        Cache cache = cacheManager.getCache("setting");

        cache.put(Constant.SETTING_CACHE_KEY, null);
    }

    public void checkWxSetting() {
        Resource resourceWx = new ClassPathResource("wxsetting.xml");
        Cache cache = cacheManager.getCache("setting");
        SAXReader readerWx = new SAXReader();
        WxSetting wxSetting = settingUtils.getWx();
        try {
            Document doc = readerWx.read(resourceWx.getInputStream());
            Element root = doc.getRootElement();

            @SuppressWarnings("unchecked")
            Iterator<Element> iter = doc.getRootElement().elementIterator();

            boolean wxAppIdMP = false;
            boolean wxAppSecretMP = false;
            boolean wxPartnerIdMP = false;
            boolean wxPartnerKeyMP = false;
            while (iter.hasNext()) {
                Element node = iter.next();

                if ("wxAppIdMP".equals(node.attributeValue("name"))) {
                    wxAppIdMP = true;
                } else if ("wxAppSecretMP".equals(node.attributeValue("name"))) {
                    wxAppSecretMP = true;
                } else if ("wxPartnerIdMP".equals(node.attributeValue("name"))) {
                    wxPartnerIdMP = true;
                } else if ("wxPartnerKeyMP".equals(node.attributeValue("name"))) {
                    wxPartnerKeyMP = true;
                }

            }

            if (!wxAppIdMP) {
                Element element = root.addElement("set");
                element.addAttribute("name", "wxAppIdMP");
                element.addAttribute("value", "");
                wxSetting.setWxAppIdMP("");
            }
            if (!wxAppSecretMP) {
                Element element = root.addElement("set");
                element.addAttribute("name", "wxAppSecretMP");
                element.addAttribute("value", "");
                wxSetting.setWxAppSecretMP("");
            }
            if (!wxPartnerIdMP) {
                Element element = root.addElement("set");
                element.addAttribute("name", "wxPartnerIdMP");
                element.addAttribute("value", "");
                wxSetting.setWxPartnerIdMP("");
            }
            if (!wxPartnerKeyMP) {
                Element element = root.addElement("set");
                element.addAttribute("name", "wxPartnerKeyMP");
                element.addAttribute("value", "");
                wxSetting.setWxPartnerKeyMP("");
            }

            OutputFormat of = OutputFormat.createPrettyPrint();
            of.setEncoding("UTF-8");
            of.setIndent(true);
            of.setIndent("\t");
            of.setNewlines(true);

            XMLWriter writer = new XMLWriter(new FileOutputStream(resourceWx.getFile()), of);
            writer.write(doc);
            writer.flush();
            writer.close();

            cache.put(Constant.SETTING_WX_CACHE_KEY, wxSetting);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Setting getDefaultSetting() {
        Setting defaultSetting = new Setting();
        defaultSetting.setWorkBegin(0);
        defaultSetting.setAllowCallDriver(false);
        defaultSetting.setLowestWorkVirtual(0D);
        defaultSetting.setInfoFeeType(InfoFeeType.none);
        defaultSetting.setInfoFee(0D);
        defaultSetting.setInfoFeeZhuan(0D);
        defaultSetting.setInfoFeeFreight(0D);
        defaultSetting.setInfoFeeErrand(0D);
        defaultSetting.setInfoFeeCityline(0D);
        defaultSetting.setCouponTicheng(false);
        defaultSetting.setUpPlatformInfo(false);
        defaultSetting.setDoubleFactor(false);
        defaultSetting.setNearDriversKm(5D);
        defaultSetting.setNearDriversAmount(5);
        defaultSetting.setNearDriversKm2(5D);
        defaultSetting.setNearDriversAmount2(5);
        defaultSetting.setRushOrderKm(0D);
        defaultSetting.setArriveToPlaceKm(5D);
        defaultSetting.setAllowRushOrder(false);
        defaultSetting.setAllowWorkCar(false);
        defaultSetting.setAllowWorkCarZhuandan(false);
        defaultSetting.setAllowDriverZhuandan(false);
        defaultSetting.setAllowDriverCancel(false);
        defaultSetting.setMustToPlace(false);
        defaultSetting.setMustMemberInfo(false);
        defaultSetting.setAllowModifyCash(true);
        defaultSetting.setAllowBaoxiao(true);
        defaultSetting.setAllowHelppayNe(true);
        defaultSetting.setInsurancesShow(true);
        defaultSetting.setEmployApplyImgNessesary(false);
        defaultSetting.setOpenHelpPay(true);
        defaultSetting.setJustPrice(true);
        defaultSetting.setPaotuiFixPrice(true);
        defaultSetting.setRevokeTime(0);
        defaultSetting.setBookTimeZhuanxian(0);
        defaultSetting.setWhichServicePhone(0);
        defaultSetting.setPayCash1(new BigDecimal(100));
        defaultSetting.setPayCash2(new BigDecimal(300));
        defaultSetting.setPayCash3(new BigDecimal(500));
        defaultSetting.setMerId("");
        defaultSetting.setAcpsdkSignCertPath("");
        defaultSetting.setAcpsdkSignCertPwd("");
        defaultSetting.setAcpProdEnc("");
        defaultSetting.setAcpProdMiddle("");
        defaultSetting.setAcpProdRoot("");
        defaultSetting.setAutoOfflineTime(0);
        defaultSetting.setSecKey("");
        defaultSetting.setAutoPaidan(false);
        defaultSetting.setAutoPaidanZhuanxian(false);
        defaultSetting.setNearPaotuiOrdersKm(5D);
        defaultSetting.setZhuanchePrePay(false);
        defaultSetting.setPaotuiPrePay(false);
        defaultSetting.setSmsMainCompany(false);
        defaultSetting.setAutoPaidanZhuanche(false);
        defaultSetting.setAllowRushOrderZhuanche(false);
        defaultSetting.setAllowRushOrderZhuanxian(false);
        defaultSetting.setAllowRushOrderErrand(false);
        defaultSetting.setAllowRushOrderFreight(false);
        defaultSetting.setFilterStr("");
        defaultSetting.setBookTimeZhuan(0);
        defaultSetting.setZhuanYuyueMax(0);
        defaultSetting.setZhuanYuyueTime(0);
        return defaultSetting;
    }
}


